from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.models import User
from django.contrib import messages
from django.utils import timezone
from django.db.models import Count, Sum, Avg
from django.http import JsonResponse, HttpResponse
from django.core.paginator import Paginator
from datetime import timedelta, date
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
import json
import csv

from story.models import Story, StoryCategory
from user.models import UserProfile, UserActivity
from interactive.models import Report, Comment, Like, Favorite
from .models import AdminLog, SystemConfig, Statistics
from .session import admin_login as admin_session_login, admin_logout as admin_session_logout

# Create your views here.

# 检查是否是管理员
def is_admin(user):
    return user.is_staff or user.is_superuser

# 管理员登录
def admin_login(request):
    # 如果用户已经以管理员身份登录，直接跳转到仪表盘
    if hasattr(request, '_admin_user') and is_admin(request._admin_user):
        return redirect('adminuser:dashboard')
        
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            
            if user is not None and is_admin(user):
                # 使用自定义会话管理器进行登录
                session_data = admin_session_login(request, user)
                
                # 记录管理员登录
                AdminLog.objects.create(
                    admin=user,
                    action_type='admin_login',
                    description=f"管理员 {username} 登录系统"
                )
                
                messages.success(request, f"欢迎回来，管理员 {username}")
                
                # 设置会话Cookie并重定向到仪表盘
                response = redirect('adminuser:dashboard')
                response.set_cookie(
                    session_data['name'],
                    session_data['value'],
                    max_age=session_data['max_age'],
                    expires=session_data['expires'],
                    path=session_data['path'],
                    domain=session_data['domain'],
                    secure=session_data['secure'],
                    httponly=session_data['httponly'],
                    samesite=session_data['samesite']
                )
                
                # 设置新的CSRF令牌
                from django.middleware.csrf import get_token
                get_token(request)
                
                return response
            else:
                messages.error(request, "登录失败，请确保您有管理员权限")
        else:
            messages.error(request, "用户名或密码错误")
    else:
        form = AuthenticationForm()
    
    # 确保在GET请求时也获取CSRF令牌
    from django.middleware.csrf import get_token
    csrf_token = get_token(request)
    
    return render(request, 'adminuser/login.html', {'form': form, 'csrf_token': csrf_token})

# 管理员注销
def admin_logout(request):
    user = getattr(request, '_admin_user', request.user)
    
    # 记录管理员注销
    if user.is_authenticated:
        AdminLog.objects.create(
            admin=user,
            action_type='admin_logout',
            description=f"管理员 {user.username} 退出系统"
        )
    
    # 使用自定义会话管理器进行注销
    cookie_data = admin_session_logout(request)
    
    # 重定向到登录页面并清除会话Cookie
    response = redirect('adminuser:admin_login')
    if cookie_data:
        response.set_cookie(
            cookie_data['name'],
            '',
            max_age=0,
            expires=cookie_data['expires'],
            path=cookie_data['path'],
            domain=cookie_data['domain']
        )
    
    messages.info(request, "您已成功退出管理系统")
    return response

# 管理员仪表盘视图装饰器
def admin_required(view_func):
    """自定义装饰器，检查管理员会话"""
    def wrapper(request, *args, **kwargs):
        if not hasattr(request, '_admin_user') or not is_admin(request._admin_user):
            messages.error(request, '您需要以管理员身份登录才能访问此页面')
            return redirect('adminuser:admin_login')
        return view_func(request, *args, **kwargs)
    return wrapper

# 管理员仪表盘
@admin_required
def admin_dashboard(request):
    # 获取今日统计数据
    today = timezone.now().date()
    today_stats, created = Statistics.objects.get_or_create(date=today)
    
    # 每次都更新统计数据确保数据准确性
    # 计算日活跃用户数
    today_stats.daily_active_users = UserActivity.objects.filter(created_at__date=today).values('user').distinct().count()
    
    # 计算新增用户数
    today_stats.new_users = User.objects.filter(date_joined__date=today).count()
    
    # 计算新增故事数
    today_stats.new_stories = Story.objects.filter(created_at__date=today).count()
    
    # 计算总浏览量
    today_stats.total_views = Story.objects.aggregate(Sum('views'))['views__sum'] or 0
    
    # 计算总点赞数
    today_stats.total_likes = Story.objects.aggregate(Sum('likes'))['likes__sum'] or 0
    
    # 计算总评论数
    today_stats.total_comments = Comment.objects.count()
    
    # 保存统计数据
    today_stats.save()
    
    # 获取近7天的统计数据
    last_week = today - timedelta(days=6)
    weekly_stats = Statistics.objects.filter(date__gte=last_week).order_by('date')
    
    # 获取最近的管理操作日志
    recent_logs = AdminLog.objects.all()[:10]
    
    # 获取待处理的举报和评论
    pending_reports = Report.objects.filter(is_handled=False).count()
    pending_comments = Comment.objects.filter(status='pending').count()
    
    context = {
        'today_stats': today_stats,
        'weekly_stats': weekly_stats,
        'recent_logs': recent_logs,
        'pending_reports': pending_reports,
        'pending_comments': pending_comments,
        'total_users': User.objects.count(),
        'total_stories': Story.objects.count(),
        'admin_user': request._admin_user  # 传递管理员用户到模板
    }
    
    # 使用普通的模板而不是专门的admin模板
    return render(request, 'adminuser/dashboard.html', context)

# 用户管理
@admin_required
def user_management(request):
    # 获取所有用户，预先加载个人资料，按注册时间倒序排列
    users = User.objects.all().select_related('profile').order_by('-date_joined')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        users = users.filter(username__icontains=search_query)
    
    # 角色筛选
    role = request.GET.get('role', '')
    if role == 'admin':
        users = users.filter(is_staff=True)
    elif role == 'banned':
        # 获取被封禁的用户
        banned_user_ids = UserProfile.objects.filter(is_banned=True).values_list('user_id', flat=True)
        users = users.filter(id__in=banned_user_ids)
    
    # 分页
    paginator = Paginator(users, 20)  # 每页显示20个用户
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 统计信息
    total_users = User.objects.count()
    admin_users = User.objects.filter(is_staff=True).count()
    banned_users = UserProfile.objects.filter(is_banned=True).count()
    
    context = {
        'page_obj': page_obj,
        'users': page_obj,  # 为了兼容性添加
        'search_query': search_query,
        'selected_role': role,
        'total_users': total_users,
        'admin_users': admin_users,
        'banned_users': banned_users,
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/user_management.html', context)

# 用户详情
@admin_required
def user_detail(request, user_id):
    user = get_object_or_404(User, id=user_id)
    user_profile, created = UserProfile.objects.get_or_create(user=user)
    
    # 用户的故事
    stories = Story.objects.filter(author=user).order_by('-created_at')
    
    # 用户的活动
    activities = UserActivity.objects.filter(user=user).order_by('-created_at')[:20]
    
    # 用户对应的举报
    reports_by_user = Report.objects.filter(reporter=user).order_by('-created_at')
    reports_against_user_stories = Report.objects.filter(story__author=user).order_by('-created_at')
    
    context = {
        'target_user': user,
        'profile': user_profile,
        'stories': stories,
        'activities': activities,
        'reports_by_user': reports_by_user,
        'reports_against_user': reports_against_user_stories,
        'admin_user': request._admin_user
    }
    return render(request, 'adminuser/user_detail.html', context)

# 封禁/解封用户
@admin_required
def toggle_ban_user(request, user_id):
    if request.method == 'POST':
        user = get_object_or_404(User, id=user_id)
        if user.is_staff or user.is_superuser:
            messages.error(request, f"无法封禁管理员用户 {user.username}")
            return redirect('adminuser:user_detail', user_id=user_id)
            
        profile, created = UserProfile.objects.get_or_create(user=user)
        
        # 切换封禁状态
        if profile.is_banned:
            profile.is_banned = False
            profile.ban_reason = ""
            profile.ban_time = None
            profile.save()
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,  # 使用管理员用户
                action_type='ban_user',
                target_user=user,
                description=f"解除封禁用户 {user.username}"
            )
            
            messages.success(request, f"已解除对用户 {user.username} 的封禁")
        else:
            # 获取封禁原因
            ban_reason = request.POST.get('ban_reason', '')
            if not ban_reason:
                messages.error(request, "请提供封禁原因")
                return redirect('adminuser:user_detail', user_id=user_id)
            
            # 设置封禁状态
            profile.is_banned = True
            profile.ban_reason = ban_reason
            profile.ban_time = timezone.now()
            profile.save()
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,  # 使用管理员用户
                action_type='ban_user',
                target_user=user,
                description=f"封禁用户 {user.username}，原因：{ban_reason}"
            )
            
            messages.success(request, f"已封禁用户 {user.username}")
        
        return redirect('adminuser:user_detail', user_id=user_id)
    
    return redirect('adminuser:user_management')

# 故事管理
@admin_required
def story_management(request):
    # 获取所有故事，预先加载作者信息，按创建时间倒序排列
    stories = Story.objects.all().select_related('author').order_by('-created_at')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        stories = stories.filter(title__icontains=search_query)
    
    # 分类筛选
    category = request.GET.get('category', '')
    if category:
        stories = stories.filter(category=category)
    
    # 草稿筛选
    is_draft = request.GET.get('is_draft', '')
    if is_draft == 'true':
        stories = stories.filter(is_draft=True)
    elif is_draft == 'false':
        stories = stories.filter(is_draft=False)
    
    # 分页
    paginator = Paginator(stories, 20)  # 每页显示20个故事
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 统计信息
    total_stories = Story.objects.count()
    draft_stories = Story.objects.filter(is_draft=True).count()
    published_stories = Story.objects.filter(is_draft=False).count()
    
    context = {
        'page_obj': page_obj,
        'stories': page_obj,  # 为了兼容性添加
        'search_query': search_query,
        'selected_category': category,
        'selected_is_draft': is_draft,
        'total_stories': total_stories,
        'draft_stories': draft_stories,
        'published_stories': published_stories,
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/story_management.html', context)

# 删除故事
@admin_required
def delete_story(request, story_id):
    if request.method == 'POST':
        story = get_object_or_404(Story, id=story_id)
        title = story.title
        author = story.author
        
        # 记录操作日志
        AdminLog.objects.create(
            admin=request._admin_user,
            action_type='delete_story',
            target_user=author,
            description=f"删除故事 '{title}'，作者：{author.username}"
        )
        
        # 删除故事
        story.delete()
        
        messages.success(request, f"已删除故事 '{title}'")
        return redirect('adminuser:story_management')
    
    return redirect('adminuser:story_management')

# 举报管理
@admin_required
def report_management(request):
    # 获取所有举报，按创建时间倒序排列
    reports = Report.objects.all().select_related('story', 'reporter', 'story__author').order_by('-created_at')
    
    # 过滤未处理的举报
    is_handled = request.GET.get('is_handled', '')
    if is_handled == 'false':
        reports = reports.filter(is_handled=False)
    elif is_handled == 'true':
        reports = reports.filter(is_handled=True)
    
    # 分页
    paginator = Paginator(reports, 20)  # 每页显示20个举报
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'reports': page_obj,  # 为了兼容性添加
        'is_handled': is_handled,
        'report_count': reports.count(),
        'unhandled_count': Report.objects.filter(is_handled=False).count(),
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/report_management.html', context)

# 处理举报
@admin_required
def handle_report(request, report_id):
    if request.method == 'POST':
        report = get_object_or_404(Report, id=report_id)
        action = request.POST.get('action', '')
        
        if action == 'dismiss':
            # 驳回举报
            report.is_handled = True
            report.save()
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='handle_report',
                target_story=report.story,
                target_user=report.reporter,
                report=report,
                description=f"驳回举报，举报ID：{report.id}"
            )
            
            messages.success(request, f"已驳回举报 #{report.id}")
        
        elif action == 'delete_story':
            # 删除被举报的故事
            story = report.story
            title = story.title
            author = story.author
            
            # 将举报标记为已处理
            report.is_handled = True
            report.save()
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='handle_report',
                target_story=story,
                target_user=author,
                report=report,
                description=f"根据举报删除故事 '{title}'，作者：{author.username}"
            )
            
            # 删除故事
            story.delete()
            
            messages.success(request, f"已根据举报删除故事 '{title}'")
        
        return redirect('adminuser:report_management')
    
    return redirect('adminuser:report_management')

# 系统设置
@admin_required
def system_settings(request):
    # 获取或创建系统配置
    settings, created = SystemConfig.objects.get_or_create(
        key='site_settings',
        defaults={
            'value': {
                'site_name': '故事生成系统',
                'site_description': 'AI故事生成和分享平台',
                'allow_registration': True,
                'allow_story_creation': True,
                'maintenance_mode': False
            },
            'description': '系统基本设置'
        }
    )
    
    settings_value = settings.value
    
    # 处理POST请求，更新配置
    if request.method == 'POST':
        # 更新网站名称
        settings_value['site_name'] = request.POST.get('site_name', '故事生成系统')
        
        # 更新是否允许注册
        settings_value['allow_registration'] = 'allow_registration' in request.POST
        
        # 更新是否允许创建故事
        settings_value['allow_story_creation'] = 'allow_story_creation' in request.POST
        
        # 更新维护模式
        settings_value['maintenance_mode'] = 'maintenance_mode' in request.POST
        
        # 保存更新后的设置
        settings.value = settings_value
        settings.save()
        
        # 记录操作日志
        AdminLog.objects.create(
            admin=request._admin_user,
            action_type='update_settings',
            description="更新系统设置"
        )
        
        messages.success(request, "系统设置已更新")
        return redirect('adminuser:system_settings')
    
    context = {
        'site_name': settings_value.get('site_name', '故事生成系统'),
        'site_description': settings_value.get('site_description', 'AI故事生成和分享平台'),
        'allow_registration': settings_value.get('allow_registration', True),
        'allow_story_creation': settings_value.get('allow_story_creation', True),
        'maintenance_mode': settings_value.get('maintenance_mode', False),
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/system_settings.html', context)

# 操作日志
@admin_required
def admin_logs(request):
    # 获取所有操作日志，预加载关联的管理员、故事和用户信息
    logs = AdminLog.objects.all().select_related('admin', 'target_story', 'target_user').order_by('-created_at')
    
    # 按操作类型筛选
    action_type = request.GET.get('action_type', '')
    if action_type:
        logs = logs.filter(action_type=action_type)
    
    # 按管理员筛选
    admin_id = request.GET.get('admin_id', '')
    if admin_id:
        logs = logs.filter(admin_id=admin_id)
    
    # 分页
    paginator = Paginator(logs, 20)  # 每页显示20条日志
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取所有管理员
    admins = User.objects.filter(is_staff=True)
    
    context = {
        'page_obj': page_obj,
        'logs': page_obj,  # 为了兼容性添加
        'action_types': AdminLog.ACTION_TYPES if hasattr(AdminLog, 'ACTION_TYPES') else [],
        'selected_action_type': action_type,
        'admins': admins,
        'selected_admin_id': admin_id,
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/admin_logs.html', context)

@admin_required
def data_analysis(request):
    """数据分析总览页面"""
    # 获取时间范围
    time_range = request.GET.get('range', 'week')
    
    # 计算时间范围
    today = timezone.now().date()
    if time_range == 'week':
        start_date = today - timedelta(days=7)
        title = "近7天数据"
    elif time_range == 'month':
        start_date = today - timedelta(days=30)
        title = "近30天数据"
    elif time_range == 'year':
        start_date = today - timedelta(days=365)
        title = "近一年数据"
    else:
        # 默认近7天
        start_date = today - timedelta(days=7)
        time_range = 'week'
        title = "近7天数据"
    
    # 获取用户增长数据
    date_list = []
    new_users_data = []
    active_users_data = []
    
    # 从Statistics获取数据
    stats = Statistics.objects.filter(date__gte=start_date).order_by('date')
    
    if stats.exists():
        for stat in stats:
            date_list.append(stat.date.strftime("%m-%d"))
            new_users_data.append(stat.new_users)
            active_users_data.append(stat.daily_active_users)
    else:
        # 如果没有数据，生成空数据
        current = start_date
        while current <= today:
            date_list.append(current.strftime("%m-%d"))
            new_users_data.append(0)
            active_users_data.append(0)
            current += timedelta(days=1)
    
    # 获取内容增长数据
    new_stories_data = []
    views_data = []
    likes_data = []
    comments_data = []
    
    if stats.exists():
        for stat in stats:
            new_stories_data.append(stat.new_stories)
            views_data.append(stat.total_views)
            likes_data.append(stat.total_likes)
            comments_data.append(stat.total_comments)
    else:
        # 如果没有数据，填充空数据
        for _ in range(len(date_list)):
            new_stories_data.append(0)
            views_data.append(0)
            likes_data.append(0)
            comments_data.append(0)
    
    # 获取分类故事分布
    categories = StoryCategory.objects.all()
    category_names = [category.name for category in categories]
    category_counts = []
    
    for category in categories:
        count = Story.objects.filter(category=category, is_draft=False).count()
        category_counts.append(count)
    
    # 获取用户角色分布
    staff_count = User.objects.filter(is_staff=True).count()
    regular_count = User.objects.filter(is_staff=False).count()
    banned_count = UserProfile.objects.filter(is_banned=True).count()
    
    # 收集总体数据
    total_users = User.objects.count()
    total_stories = Story.objects.filter(is_draft=False).count()
    total_views = Story.objects.filter(is_draft=False).aggregate(Sum('views'))['views__sum'] or 0
    total_likes = Story.objects.filter(is_draft=False).aggregate(Sum('likes'))['likes__sum'] or 0
    
    # 计算平均值
    avg_views_per_story = total_views / total_stories if total_stories > 0 else 0
    avg_likes_per_story = total_likes / total_stories if total_stories > 0 else 0
    
    # 准备上下文数据
    context = {
        'title': title,
        'time_range': time_range,
        'date_list': date_list,
        'new_users_data': new_users_data,
        'active_users_data': active_users_data,
        'new_stories_data': new_stories_data,
        'views_data': views_data,
        'likes_data': likes_data,
        'comments_data': comments_data,
        'category_names': category_names,
        'category_counts': category_counts,
        'staff_count': staff_count,
        'regular_count': regular_count,
        'banned_count': banned_count,
        'total_users': total_users,
        'total_stories': total_stories,
        'total_views': total_views,
        'total_likes': total_likes,
        'avg_views_per_story': round(avg_views_per_story, 2),
        'avg_likes_per_story': round(avg_likes_per_story, 2),
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/data_analysis.html', context)

@admin_required
def user_analysis(request):
    """用户数据分析页面"""
    # 获取时间范围
    time_range = request.GET.get('range', 'week')
    
    # 计算时间范围
    today = timezone.now().date()
    if time_range == 'week':
        start_date = today - timedelta(days=7)
        title = "近7天用户数据"
    elif time_range == 'month':
        start_date = today - timedelta(days=30)
        title = "近30天用户数据"
    elif time_range == 'year':
        start_date = today - timedelta(days=365)
        title = "近一年用户数据"
    else:
        # 默认近7天
        start_date = today - timedelta(days=7)
        time_range = 'week'
        title = "近7天用户数据"
    
    # 用户注册时间分布
    signup_date_counts = User.objects.filter(
        date_joined__date__gte=start_date
    ).extra(
        select={'day': 'date(date_joined)'}
    ).values('day').annotate(count=Count('id')).order_by('day')
    
    date_list = []
    signup_counts = []
    
    current = start_date
    signup_dict = {item['day'].strftime('%Y-%m-%d'): item['count'] for item in signup_date_counts}
    
    while current <= today:
        date_str = current.strftime('%Y-%m-%d')
        date_list.append(current.strftime("%m-%d"))
        signup_counts.append(signup_dict.get(date_str, 0))
        current += timedelta(days=1)
    
    # 最活跃用户统计
    most_active_users = UserActivity.objects.filter(
        created_at__date__gte=start_date
    ).values('user__username').annotate(
        activity_count=Count('id')
    ).order_by('-activity_count')[:10]
    
    active_usernames = [item['user__username'] for item in most_active_users]
    active_counts = [item['activity_count'] for item in most_active_users]
    
    # 用户活动类型分布
    activity_types = UserActivity.objects.filter(
        created_at__date__gte=start_date
    ).values('activity_type').annotate(
        count=Count('id')
    ).order_by('-count')
    
    activity_type_names = [item['activity_type'] for item in activity_types]
    activity_type_counts = [item['count'] for item in activity_types]
    
    # 用户设备/浏览器统计
    # 注意：这需要在用户活动模型中添加设备/浏览器字段
    # 这里先模拟一些数据
    browsers = ['Chrome', 'Firefox', 'Safari', 'Edge', 'Other']
    browser_counts = [45, 25, 15, 10, 5]  # 模拟数据
    
    # 准备上下文数据
    context = {
        'title': title,
        'time_range': time_range,
        'date_list': date_list,
        'signup_counts': signup_counts,
        'active_usernames': active_usernames,
        'active_counts': active_counts,
        'activity_type_names': activity_type_names,
        'activity_type_counts': activity_type_counts,
        'browsers': browsers,
        'browser_counts': browser_counts,
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/user_analysis.html', context)

@admin_required
def content_analysis(request):
    """内容数据分析页面"""
    # 获取时间范围
    time_range = request.GET.get('range', 'week')
    
    # 计算时间范围
    today = timezone.now().date()
    if time_range == 'week':
        start_date = today - timedelta(days=7)
        title = "近7天内容数据"
    elif time_range == 'month':
        start_date = today - timedelta(days=30)
        title = "近30天内容数据"
    elif time_range == 'year':
        start_date = today - timedelta(days=365)
        title = "近一年内容数据"
    else:
        # 默认近7天
        start_date = today - timedelta(days=7)
        time_range = 'week'
        title = "近7天内容数据"
    
    # 故事创建时间分布
    story_date_counts = Story.objects.filter(
        created_at__date__gte=start_date
    ).extra(
        select={'day': 'date(created_at)'}
    ).values('day').annotate(count=Count('id')).order_by('day')
    
    date_list = []
    story_counts = []
    
    current = start_date
    story_dict = {item['day'].strftime('%Y-%m-%d'): item['count'] for item in story_date_counts}
    
    while current <= today:
        date_str = current.strftime('%Y-%m-%d')
        date_list.append(current.strftime("%m-%d"))
        story_counts.append(story_dict.get(date_str, 0))
        current += timedelta(days=1)
    
    # 最受欢迎故事统计
    popular_stories = Story.objects.filter(
        is_draft=False
    ).order_by('-views', '-likes')[:10]
    
    # 分类故事数量统计
    categories = StoryCategory.objects.all()
    category_names = [category.name for category in categories]
    category_counts = []
    
    for category in categories:
        count = Story.objects.filter(category=category, is_draft=False).count()
        category_counts.append(count)
    
    # AI生成与人工创作对比 - 使用模拟数据，因为模型中没有is_ai_generated字段
    total_stories = Story.objects.filter(is_draft=False).count()
    # 假设60%的故事是AI生成的
    ai_generated_count = int(total_stories * 0.6)
    human_written_count = total_stories - ai_generated_count
    
    # 故事长度分布
    # 这里需要在Story模型中添加字段或在存储时计算字数
    # 这里模拟一些数据
    length_ranges = ['1000字以下', '1000-3000字', '3000-5000字', '5000-10000字', '10000字以上']
    length_counts = [30, 40, 15, 10, 5]  # 模拟数据
    
    # 收集统计数据
    total_stories = Story.objects.filter(is_draft=False).count()
    avg_views = Story.objects.filter(is_draft=False).aggregate(Avg('views'))['views__avg'] or 0
    avg_likes = Story.objects.filter(is_draft=False).aggregate(Avg('likes'))['likes__avg'] or 0
    
    # 准备上下文数据
    context = {
        'title': title,
        'time_range': time_range,
        'date_list': date_list,
        'story_counts': story_counts,
        'popular_stories': popular_stories,
        'category_names': category_names,
        'category_counts': category_counts,
        'ai_generated_count': ai_generated_count,
        'human_written_count': human_written_count,
        'length_ranges': length_ranges,
        'length_counts': length_counts,
        'story_count': total_stories,
        'story_growth': 5.2,  # 示例数据
        'avg_read_time': 4.5,  # 示例数据
        'read_time_growth': 3.2,  # 示例数据
        'avg_content_length': 850,  # 示例数据
        'content_length_growth': 2.1,  # 示例数据
        'avg_engagement_rate': 12.4,  # 示例数据
        'engagement_growth': 5.3,  # 示例数据
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/content_analysis.html', context)

@admin_required
def interaction_analysis(request):
    """互动数据分析页面"""
    # 获取时间范围
    time_range = request.GET.get('range', 'week')
    
    # 计算时间范围
    today = timezone.now().date()
    if time_range == 'week':
        start_date = today - timedelta(days=7)
        title = "近7天互动数据"
    elif time_range == 'month':
        start_date = today - timedelta(days=30)
        title = "近30天互动数据"
    elif time_range == 'year':
        start_date = today - timedelta(days=365)
        title = "近一年互动数据"
    else:
        # 默认近7天
        start_date = today - timedelta(days=7)
        time_range = 'week'
        title = "近7天互动数据"
    
    # 点赞、评论、收藏按天统计
    like_date_counts = Like.objects.filter(
        created_at__date__gte=start_date
    ).extra(
        select={'day': 'date(created_at)'}
    ).values('day').annotate(count=Count('id')).order_by('day')
    
    comment_date_counts = Comment.objects.filter(
        created_at__date__gte=start_date
    ).extra(
        select={'day': 'date(created_at)'}
    ).values('day').annotate(count=Count('id')).order_by('day')
    
    favorite_date_counts = Favorite.objects.filter(
        created_at__date__gte=start_date
    ).extra(
        select={'day': 'date(created_at)'}
    ).values('day').annotate(count=Count('id')).order_by('day')
    
    date_list = []
    like_counts = []
    comment_counts = []
    favorite_counts = []
    
    current = start_date
    like_dict = {item['day'].strftime('%Y-%m-%d'): item['count'] for item in like_date_counts}
    comment_dict = {item['day'].strftime('%Y-%m-%d'): item['count'] for item in comment_date_counts}
    favorite_dict = {item['day'].strftime('%Y-%m-%d'): item['count'] for item in favorite_date_counts}
    
    while current <= today:
        date_str = current.strftime('%Y-%m-%d')
        date_list.append(current.strftime("%m-%d"))
        like_counts.append(like_dict.get(date_str, 0))
        comment_counts.append(comment_dict.get(date_str, 0))
        favorite_counts.append(favorite_dict.get(date_str, 0))
        current += timedelta(days=1)
    
    # 每个分类的平均互动统计
    categories = StoryCategory.objects.all()
    category_names = [category.name for category in categories]
    avg_likes = []
    avg_comments = []
    
    for category in categories:
        stories = Story.objects.filter(category=category, is_draft=False)
        story_count = stories.count()
        if story_count > 0:
            total_likes = stories.aggregate(Sum('likes'))['likes__sum'] or 0
            total_comments = Comment.objects.filter(story__category=category).count()
            avg_likes.append(round(total_likes / story_count, 2))
            avg_comments.append(round(total_comments / story_count, 2))
        else:
            avg_likes.append(0)
            avg_comments.append(0)
    
    # 用户互动时间分布
    hour_distribution = Comment.objects.filter(
        created_at__date__gte=start_date
    ).extra(
        select={'hour': 'hour(created_at)'}
    ).values('hour').annotate(count=Count('id')).order_by('hour')
    
    hours = list(range(24))
    hour_counts = [0] * 24
    
    for item in hour_distribution:
        hour_counts[item['hour']] = item['count']
    
    # 准备上下文数据
    context = {
        'title': title,
        'time_range': time_range,
        'date_list': date_list,
        'like_counts': like_counts,
        'comment_counts': comment_counts,
        'favorite_counts': favorite_counts,
        'category_names': category_names,
        'avg_likes': avg_likes,
        'avg_comments': avg_comments,
        'hours': hours,
        'hour_counts': hour_counts,
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/interaction_analysis.html', context)

# 评论管理
@admin_required
def comment_management(request):
    """评论管理页面"""
    # 获取所有评论，按创建时间倒序排列
    comments = Comment.objects.all().select_related('user', 'story', 'story__author').order_by('-created_at')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        comments = comments.filter(content__icontains=search_query)
    
    # 评论状态筛选
    status = request.GET.get('status', '')
    if status:
        comments = comments.filter(status=status)
    
    # 分页
    paginator = Paginator(comments, 20)  # 每页显示20条评论
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 统计信息
    total_comments = Comment.objects.count()
    pending_comments = Comment.objects.filter(status='pending').count()
    approved_comments = Comment.objects.filter(status='approved').count()
    rejected_comments = Comment.objects.filter(status='rejected').count()
    
    context = {
        'page_obj': page_obj,
        'comments': page_obj,
        'search_query': search_query,
        'selected_status': status,
        'total_comments': total_comments,
        'pending_comments': pending_comments,
        'approved_comments': approved_comments,
        'rejected_comments': rejected_comments,
        'admin_user': request._admin_user
    }
    
    return render(request, 'adminuser/comment_management.html', context)

# 处理评论
@admin_required
def handle_comment(request, comment_id):
    """处理评论（批准、拒绝或删除）"""
    if request.method == 'POST':
        comment = get_object_or_404(Comment, id=comment_id)
        action = request.POST.get('action', '')
        
        if action == 'approve':
            # 批准评论
            comment.status = 'approved'
            comment.save()
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='approve_comment',
                description=f"批准了评论 ID:{comment.id}，作者:{comment.user.username}"
            )
            
            messages.success(request, f"已批准 ID 为 {comment.id} 的评论")
        
        elif action == 'reject':
            # 拒绝评论
            comment.status = 'rejected'
            rejected_reason = request.POST.get('rejected_reason', '')
            comment.rejected_reason = rejected_reason
            comment.save()
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='reject_comment',
                description=f"拒绝了评论 ID:{comment.id}，作者:{comment.user.username}，原因:{rejected_reason}"
            )
            
            messages.success(request, f"已拒绝 ID 为 {comment.id} 的评论")
        
        elif action == 'delete':
            # 删除评论
            user = comment.user
            story = comment.story
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='delete_comment',
                target_user=user,
                target_story=story,
                description=f"删除了评论 ID:{comment.id}，作者:{user.username}，故事:{story.title}"
            )
            
            # 删除评论
            comment.delete()
            
            messages.success(request, f"已删除评论")
        
        return redirect('adminuser:comment_management')
    
    return redirect('adminuser:comment_management')

# 批量处理评论
@admin_required
def batch_handle_comments(request):
    """批量处理评论（批准、拒绝或删除）"""
    if request.method == 'POST':
        comment_ids = request.POST.getlist('comment_ids')
        action = request.POST.get('action', '')
        
        if not comment_ids:
            messages.error(request, "请至少选择一条评论进行操作")
            return redirect('adminuser:comment_management')
        
        # 获取评论对象
        comments = Comment.objects.filter(id__in=comment_ids)
        
        if comments.count() == 0:
            messages.warning(request, "未找到所选评论")
            return redirect('adminuser:comment_management')
        
        if action == 'approve':
            # 批量批准评论
            count = comments.update(status='approved')
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='approve_comments',
                description=f"批量批准了 {count} 条评论，ID: {', '.join(str(id) for id in comment_ids)}"
            )
            
            messages.success(request, f"已批量批准 {count} 条评论")
        
        elif action == 'reject':
            # 批量拒绝评论
            rejected_reason = request.POST.get('rejected_reason', '批量拒绝')
            count = comments.update(status='rejected', rejected_reason=rejected_reason)
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='reject_comments',
                description=f"批量拒绝了 {count} 条评论，原因: {rejected_reason}，ID: {', '.join(str(id) for id in comment_ids)}"
            )
            
            messages.success(request, f"已批量拒绝 {count} 条评论")
        
        elif action == 'delete':
            # 获取评论信息用于日志记录
            comment_info = []
            for comment in comments:
                comment_info.append(f"ID:{comment.id}, 作者:{comment.user.username}")
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='delete_comments',
                description=f"批量删除了 {len(comment_ids)} 条评论，详情: {'; '.join(comment_info)}"
            )
            
            # 批量删除评论
            count = comments.delete()[0]
            
            messages.success(request, f"已批量删除 {count} 条评论")
        
        return redirect('adminuser:comment_management')
    
    return redirect('adminuser:comment_management')

# 批量处理举报
@admin_required
def batch_handle_reports(request):
    """批量处理举报（驳回或删除故事）"""
    if request.method == 'POST':
        report_ids = request.POST.getlist('report_ids')
        action = request.POST.get('action', '')
        
        if not report_ids:
            messages.error(request, "请至少选择一个举报进行操作")
            return redirect('adminuser:report_management')
        
        # 获取举报对象
        reports = Report.objects.filter(id__in=report_ids, is_handled=False)
        
        if reports.count() == 0:
            messages.warning(request, "未找到有效的未处理举报")
            return redirect('adminuser:report_management')
            
        if action == 'dismiss':
            # 批量驳回举报
            count = reports.update(is_handled=True)
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='dismiss_reports',
                description=f"批量驳回了 {count} 个举报，ID: {', '.join(str(id) for id in report_ids)}"
            )
            
            messages.success(request, f"已批量驳回 {count} 个举报")
        
        elif action == 'delete_story':
            # 获取故事和举报信息用于日志记录
            story_info = []
            for report in reports:
                story = report.story
                story_info.append(f"ID:{story.id}, 标题:{story.title}, 作者:{story.author.username}")
            
            # 记录操作日志
            AdminLog.objects.create(
                admin=request._admin_user,
                action_type='delete_stories',
                description=f"通过批量处理举报删除了 {len(story_info)} 个故事，详情: {'; '.join(story_info)}"
            )
            
            # 对每个报告单独处理
            deleted_count = 0
            for report in reports:
                # 标记举报为已处理
                report.is_handled = True
                report.save()
                
                # 删除故事
                story = report.story
                story.delete()
                deleted_count += 1
            
            messages.success(request, f"已批量删除 {deleted_count} 个故事并处理对应举报")
        
        return redirect('adminuser:report_management')
    
    return redirect('adminuser:report_management')
